#include <opencv2/opencv.hpp>

#include <string>

#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fstream>

using namespace std;

int main(int argc, char const *argv[])
{
    int i = 0;
    const string img_load_base = argv[1]; //"/home/yjy/dataset/palmprint_dectection/tmp2/";
    string file_name_color;
    dirent *filename;
    cv::Mat image, total, dx, dy, tmp;

    total = total.zeros(cv::Size(stoi(argv[2]), stoi(argv[3])), CV_64F);
    DIR *dir = opendir(img_load_base.c_str());

    while ((filename = readdir(dir)) != NULL)
    {
        if (strcmp(filename->d_name, ".") == 0 ||
            strcmp(filename->d_name, "..") == 0)
            continue;

        file_name_color = filename->d_name;
        image = cv::imread(img_load_base + file_name_color);

        if (image.type() != CV_8UC1)
            cv::cvtColor(image, image, cv::COLOR_BGR2GRAY);
        cv::Sobel(image, dx, CV_16S, 1, 0, 3, 1);
        cv::Sobel(image, dy, CV_16S, 0, 1, 3, 1);
        cv::convertScaleAbs(dx, dx);
        cv::convertScaleAbs(dy, dy);
        cv::addWeighted(dx, 0.5, dy, 0.5, 0, image);
        cv::adaptiveThreshold(image, image, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 63, -5);
        //debug
        // cv::imshow("img show window", image);
        // cv::waitKey(0);

        image.convertTo(image, CV_64F);
        cv::add(image, total, total);

        i++;
    }

    tmp = cv::Mat(stoi(argv[3]), stoi(argv[2]), CV_64F, cv::Scalar((double)i));
    cv::divide(total, tmp, total);
    total.convertTo(total, CV_8U);

    cv::imwrite(img_load_base + "A_total_image.bmp", total);
    return 0;
}
